import os
import sys
import jpype
from myapp.pp_py.src.config.config import PPConfig
from myapp.pp_py.src.utils.map_converter import load_map
from myapp.pp_py.src.utils.yaml_reader import load_yaml

# 获取 src 所在目录的父路径（即 pp_py 目录）
work_dir = os.path.dirname(os.path.abspath(__file__))
src_path = os.path.join(work_dir, 'myapp', 'pp_py', 'src')
src_parent_path = os.path.dirname(os.path.abspath(src_path))

# 添加到 sys.path
if src_parent_path not in sys.path:
    sys.path.append(src_parent_path)

def main():
    """Run administrative tasks."""
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    # 只在非重载进程中加载map对象
    if os.environ.get('RUN_MAIN') != 'true':
        print("Watcher process started, waiting for code changes...")
    else:
        # 加载全局map对象
        print("开始加载数据和配置...")
        work_dir = os.path.dirname(os.path.abspath(__file__))
        bin_path = os.path.join(work_dir, 'data', 'map_with_buildings.bin')
        map = load_map(bin_path)
        PPConfig.global_map = map
        # 加载yaml配置
        yaml_path = os.path.join(work_dir, 'data', 'config.yaml')
        PPConfig.yaml_path = yaml_path
        PPConfig.pp_config = load_yaml(yaml_path)
        # 加载路网导航器
        jar_path = os.path.join(work_dir, 'data', 'MyGraphhopper-1.0-SNAPSHOT.jar')
        jvm_path = jpype.getDefaultJVMPath()
        jpype.startJVM(jvmpath=jvm_path, classpath=[jar_path])
        print("数据和配置加载完成,启动Django服务!")

    # 执行命令行参数
    execute_from_command_line(sys.argv)

if __name__ == "__main__":
    main()
